
var CurrentUser;    //Global variable

function getName() {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    CurrentUser = user;   //global variable
    if (user) {
        console.log("Currently logged in:  " + user["name"]);
        document.getElementById("name-goes-here").innerText = user["name"];
    } else {
        console.log("No one is logged in");
    }
}
getName(); //run the function

function populateHistory() { 
 
    // find out who is logged in  
    var who = JSON.parse(localStorage.getItem("loggedinUser"));  
    var users = JSON.parse(localStorage.getItem("users"));    
    let email = who["email"];                                 
    const user = users.find(u => u.email === email);          
 
    // get information for that user who is logged in 
    if (user) { 
         historyArray = user["history"];

         historyArray.forEach((hist,index) => { 
let historyCardTemplate = document.getElementById("postCardTemplate"); 
let historyCardGroup = document.getElementById("history-goes-here"); 
let onecard = historyCardTemplate.content.cloneNode(true);

onecard.querySelector(".date").innerHTML = hist.date; 
onecard.querySelector(".count").innerHTML = hist.calories; 
onecard.querySelector(".card-description").innerHTML = hist.details; 
onecard.querySelector('.card-image').src =" ./images/"+ hist.imageName; 
onecard.querySelector('.deleteButton').onclick = () => deleteHistory(index); 
historyCardGroup.appendChild(onecard); 

}) 
    } else { 
        console.log("No one is logged in"); 
    } 
} 
populateHistory();
 
    function deleteHistory(id) { 
var users = JSON.parse(localStorage.getItem("users")); 
const person = users.find(u => u.email === CurrentUser["email"]); 
} 
function deleteHistory(id) { 
var users = JSON.parse(localStorage.getItem("users")); 
const person = users.find(u => u.email === CurrentUser["email"]); 
// Get a confirmation from User before you delete 
if (confirm("Are you sure you want to delete this history: " + person.history[id].details + 
" on " + person.history[id].date)) { 
} 
// remove this item from array at index position "id" 
person.history.splice(id); 
localStorage.setItem("users", JSON.stringify(users)); 
alert('History data deleted successfully!'); 
location.reload();
} 
